package com.superb.common.redis.annotation;

import com.superb.common.redis.key.RedisLockKey;
import com.superb.common.redis.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.time.Duration;

/**
 * redission 分布式方法锁注解实现
 * @Author: ajie
 * @CreateTime: 2024-07-24 10:28
 */
@Slf4j
@Aspect
@Component
public class SuperbLockAspect {

    @Around("@annotation(superbLock)")
    public Object around(ProceedingJoinPoint joinPoint, SuperbLock superbLock) {
        log.debug("[开始]执行RedisLock环绕通知,获取Redis分布式锁开始");
        RedisLockKey lockKey = new RedisLockKey(superbLock.value(), Duration.of(superbLock.leaseTime(), superbLock.timeUnit()));
        // 方法执行前加锁
        RedisUtils.build().lock().lock(lockKey);
        Object proceed = null;
        try {
            log.info("获取Redis分布式锁[成功]，加锁完成，开始执行业务逻辑...");
            proceed = joinPoint.proceed();
        } catch (Throwable e) {
            log.error("获取Redis分布式锁[异常]，加锁失败", e);
        } finally {
            // 释放锁
            RedisUtils.build().lock().unlock(lockKey);
        }
        log.debug("释放Redis分布式锁[成功]，解锁完成，结束业务逻辑...");
        return proceed;
    }

}
